
ALTER    proc sp_update_end_user_default_shippingAddress
@end_user_id int, @address_id int

AS


BEGIN

	declare @sales_order_id int
	declare @present_address_id int
	declare @update_address_cursor CURSOR
	
	/*
	 * Update the Default Shipping AddressID in Customer only if it is not same
	 */
	
	SELECT @present_address_id = E_Default_Shipping_Address_ID From End_User_Table
		WHERE End_User_ID = @end_user_id
	
	if(@present_address_id <> @address_id)
	begin
		DELETE from End_User_Shipping_Address_Table 
			WHERE End_User_ID = @end_user_id and
			Address_ID = @address_id

		UPDATE End_User_Table SET E_Default_Shipping_Address_ID = @address_id
			WHERE End_User_ID = @end_user_id
		
		-- insert previous default address id not present in customer shipping address table
		if not exists (SELECT * FROM End_User_Shipping_Address_Table 
			WHERE End_User_ID = @end_user_id and Address_ID = @present_address_id)
		begin
			INSERT INTO End_User_Shipping_Address_Table 
				VALUES(@end_user_id,@present_address_id,CURRENT_TIMESTAMP)
		end

		
	end
	
	/*
	 * Update the ShippingAddress Id for all the Sales_orders not Shipped
	 */
/*
	set @update_address_cursor = CURSOR FOR
	SELECT DISTINCT SalesOrder_ID from fn_load_view_orders ('0','0',1,'BACKLOG')

	open @update_address_cursor		
		fetch next from @update_address_cursor into @sales_order_id
	
		while @@fetch_status = 0
		begin		

			UPDATE Sales_Order SET SO_Shipping_Address_ID = @address_id
				WHERE SalesOrder_ID = @sales_order_id and 
				Customer_ID = @customer_id

			fetch next from @update_address_cursor into @sales_order_id
		end
			
		close @update_address_cursor
		deallocate @update_address_cursor

*/
END
